<template>
  <el-dialog
    :title="type === 'TEACH' ? '发起备课' : '创建培训'"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    class="dialog"
    width="656px"
  >
    <div class="modalBox">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-position="top"
        class="ruleForm"
      >
        <el-form-item label="封面图" prop="originImg">
          <div class="uploadArea">
            <el-upload
              class="cover-uploader"
              :show-file-list="false"
              action=""
              :before-upload="beforeCoverUpload"
            >
              <img
                v-if="ruleForm.originImg"
                :src="`${$basAssetsUrl}${ruleForm.originImg}`"
                class="cover"
              />
              <i v-else class="el-icon-plus cover-uploader-icon"></i>
            </el-upload>
            <div class="tips">
              上传封面图，支持jpg、png格式。
            </div>
          </div>
        </el-form-item>
        <el-form-item label="标题" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="分类" prop="name" v-if="type === 'TRAIN'">
          <el-select style="width: 100%" v-model="ruleForm.categoryId" placeholder="请选择分类">
            <el-option
              v-for="item in typeList"
              :key="item.value"
              :label="item.name"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="timeVal">
          <el-date-picker
            style="width: 100%"
            v-model="ruleForm.timeVal"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <el-input
            placeholder="请输入简介"
            type="textarea"
            :rows="3"
            resize="none"
            v-model="ruleForm.description"
          ></el-input>
        </el-form-item>
        <el-form-item label="流程">
          <el-input
            placeholder="请输入流程"
            type="textarea"
            :rows="3"
            resize="none"
            v-model="ruleForm.flow"
          ></el-input>
        </el-form-item>
        <el-form-item label="班级群">
          <el-input
            placeholder="请输入班级群"
            v-model="ruleForm.question"
          ></el-input>
          <div class="uploadArea">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              action=""
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="ruleForm.qrImg"
                :src="`${$basAssetsUrl}${ruleForm.qrImg}`"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <div class="tips">
              上传班级群二维码，支持jpg、png格式。
            </div>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm('ruleForm')">
        创 建
      </el-button>
    </span>
  </el-dialog>
</template>

<script>
import { fileUpload } from '@/api/common';
import { addTeach } from '@/api/teach';
import { getUserInfo } from '@/utils/auth'
import { mapActions } from 'vuex';

export default {
  name: 'AddFrom',
  props: {
    type: {
      type: String,
      default: 'TEACH'
    }
  },
  data() {
    return {
      dialogVisible: false,
      ruleForm: {
        name: '', // 名称
        originImg: '', // 封面图 原始图
        description: '', // 简介
        flow: '', // 流程说明
        question: '', // 答疑群说明
        qrImg: '', // 二维码图片地址
        promoter: '', // 发起人
        type: '', // 类型,TRAIN:培训,TEACH:集体备课
        beginTime: '', // 开始时间
        endTime: '', // 结束时间
        timeVal: [],
        categoryId: '', // 分类ID

        objectId: '', // 主id 新增不传
        thumbImg: '', // 封面图 缩略图
        labelName: '', // 标签
        speaker: '', // 主讲人
        sumary: '', // 总结
        sumaryFile: '', // 总结文件地址路径
        sumaryType: '', // 总结类型 PRIVATE 私有 PUBLIC 公开
      },
      rules: {
        originImg: [
          { required: true, message: '请上传封面图', trigger: 'change' },
        ],
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        description: [
          { required: true, message: '请填写简介', trigger: 'blur' },
        ],
        timeVal: [
          { required: true, message: '请选择时间', trigger: 'change' },
        ]
      },
      typeList: []
    };
  },
  computed: {
    userInfo() {
      return getUserInfo() || {}
    }
  },
  mounted() {
    if(this.type === 'TRAIN') {
      this.getTpye();
    }
  },
  methods: {
    ...mapActions(['getAllType']),
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const params = {
            name: this.ruleForm.name,
            originImg: this.ruleForm.originImg,
            description: this.ruleForm.description,
            flow: this.ruleForm.flow,
            qrImg: this.ruleForm.qrImg,
            question: this.ruleForm.question,
            type: this.type,
            promoter: this.userInfo.name,
            beginTime: this.ruleForm.timeVal[0],
            endTime: this.ruleForm.timeVal[1],
            categoryId: this.ruleForm.categoryId
          }
          await addTeach(params);
          this.$message.success('创建成功');
          this.ruleForm = {
            name: '', // 名称
            originImg: '', // 封面图 原始图
            description: '', // 简介
            flow: '', // 流程说明
            question: '', // 答疑群说明
            qrImg: '', // 二维码图片地址
            promoter: '', // 发起人
            type: '', // 类型,TRAIN:培训,TEACH:集体备课
            beginTime: '', // 开始时间
            endTime: '', // 结束时间
            timeVal: [],
            categoryId: '', // 分类ID
            objectId: '', // 主id 新增不传
            thumbImg: '', // 封面图 缩略图
            labelName: '', // 标签
            speaker: '', // 主讲人
            sumary: '', // 总结
            sumaryFile: '', // 总结文件地址路径
            sumaryType: '', // 总结类型 PRIVATE 私有 PUBLIC 公开
          }
          this.$emit('success');
          this.dialogVisible = false;
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 用户点击上传按钮时，不会触发默认上传
    beforeAvatarUpload(file) {
      console.log(file);
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        return this.$message.error('上传班级群二维码，只支持JPG、PNG格式!');
      }
      if (!isLt2M) {
        return this.$message.error('上传班级群二维码图片大小不能超过 2MB!');
      }
      this.uploadFile(file);
      return false; // 阻止默认上传行为
    },

    // 上传
    async uploadFile(file) {
      try {
        // 创建 FormData 对象
        let formData = new FormData();
        formData.append('file', file); // 'file' 是你服务器端接收上传文件的参数名
        const resData = await fileUpload(formData);
        this.ruleForm.qrImg = resData;
      } catch (error) {
        console.error(error);
      }
    },
    // 用户点击上传按钮时，不会触发默认上传
    beforeCoverUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        return this.$message.error('上传封面，只支持JPG、PNG格式!');
      }
      if (!isLt2M) {
        return this.$message.error('上传封面图片大小不能超过 2MB!');
      }
      this.uploadFileCover(file);
      return false; // 阻止默认上传行为
    },

    // 上传
    async uploadFileCover(file) {
      try {
        // 创建 FormData 对象
        let formData = new FormData();
        formData.append('file', file); // 'file' 是你服务器端接收上传文件的参数名
        const resData = await fileUpload(formData);
        this.ruleForm.originImg = resData;
      } catch (error) {
        console.error(error);
      }
    },
    // 获取分类
    async getTpye() {
      try {
        const resData = await this.getAllType({ type: 'TRAIN' });
        this.typeList = [
          ...resData.map((item) => {
            return {
              name: item.name,
              value: item.objectId,
            };
          }),
        ];
      } catch (error) {
        console.error(error);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.dialog {
  ::v-deep .el-dialog {
    border-radius: 8px;
  }

  ::v-deep .el-upload {
    border: 1px solid #c8c8c8;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  ::v-deep .el-upload:hover {
    border-color: $primary-color;
  }
  .modalBox {
    height: 600px;
    overflow-y: auto;
    padding-right: 30px;
    box-sizing: border-box;
  }
  .avatar-uploader {
    margin-top: 20px;
    .avatar-uploader-icon {
      font-size: 28px;
      color: #c8c8c8;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  }
  .cover-uploader {
    .cover-uploader-icon {
      font-size: 28px;
      color: #c8c8c8;
      width: 326px;
      height: 196px;
      line-height: 196px;
      text-align: center;
    }
    .cover {
      width: 326px;
      height: 196px;
      display: block;
    }
  }
  .uploadArea {
    display: flex;
    .tips {
      font-size: 12px;
      font-weight: 400;
      color: #c6c6c6;
      padding-top: 10px;
      padding-left: 10px;
      box-sizing: border-box;
    }
  }
  
  ::v-deep .el-dialog__body {
    padding: 0px 20px 10px;
  }
  ::v-deep .el-form--label-top .el-form-item__label {
    padding: 0;
  }
  ::v-deep .el-form-item {
    margin-bottom: 16px;
  }
  ::v-deep .el-form-item__content {
    line-height: 28px;
  }
}
</style>
